<?php 
/**
 * 
 * 营销邮件（EDM）相关API
 * @author David
 *
 */
class Helper_BSS_API_BMAIL
{
	
	static $client;
	static $token;
	
	static $uname;
	static $upass;
	
	public static $uaccountList = array(
		"reg_edm" => array(
			"name_id" => "regedm", 
			"pass_id" => "regedm"
		),
		"ebay_edm" => array(
			"name_id" => "ebayedm", 
			"pass_id" => "ebayedm"
		)
	);
	
	static function initAccount($accountType="reg_edm") {
		
		self::$uname = self::$uaccountList[$accountType]["name_id"];
		self::$upass = self::$uaccountList[$accountType]["pass_id"];
		
	}
	
	static private function _getToken() 
	{
		include_once Q::ini('custom_system/lib_dir').'XML/RPC2/Client.php';
		self::$client = XML_RPC2_Client::create(Q::ini('custom_api/bmail_api_uri'));
    	self::$token =  self::$client->login(Q::ini('custom_api/bmail_api_'.self::$uname.'_uname'), Q::ini('custom_api/bmail_api_'.self::$upass.'_upasswd'));
   	
	}
	
	/**
	 * 
	 * 新增邮件
	 * @param string $name 邮件名称    （e.g.20120602_iwc_metallic_lady_i_hone_cases）
	 * @param string $subjects 主题
	 * @param string $scheduleDate 发送时间
	 * @param string $to_listid 目标 list id
	 * @param string $from_mail 发信邮箱
	 * @param string $from_name 发信人
	 * @param string $reply_email 回邮邮箱
	 * @param string $html_contents 内容 （ html格式）
	 * @return boolean 发送成功 则返回 true，否则返回 false
	 * 
	 */
	static function createEDM($name, $subjects, $scheduleDate, $to_listid, $from_mail, $from_name, $reply_email, $html_contents) 
	{
		
		self::_getToken();
    	 
    	if (
    		!empty($name) && !empty($subjects) && !empty($scheduleDate) && !empty($html_contents)
    		&& !empty($to_listid) && !empty($from_mail) && !empty($from_name) && !empty($reply_email)
    	) {
		    
		    $emailDetail['fromEmail'] = $from_mail;
		    $emailDetail['fromName'] = $from_name;
		    $emailDetail['replyEmail'] = $reply_email;
		    
		    $emailDetail['toListID'] = intval($to_listid);
		    $emailDetail['templateContent'] = $html_contents;
		    $emailDetail['webpageVersion'] = true;
		    $emailDetail['permissionReminderMessage'] = 'You are receiving this email because of your relationship with ' . $from_name . '. Unsubscribe is available at the bottom of this email.';
		    
		    
		    $emailDetail['googleAnalyticsCampaign'] = $emailDetail['emailName'] = $name;
		    $emailDetail['subject'] = $subjects;
		    $emailDetail['scheduleDate'] = $scheduleDate;
		    
		    $newEmailID = self::$client->emailCreate(self::$token, $emailDetail);
		
		    if (!empty($newEmailID)) {
		    	
		    	$emailSendTestSuccess = self::$client->emailSendTest(self::$token, $newEmailID, $from_mail);
		    	$details = self::$client->emailGetDetail(self::$token, $newEmailID);
		    	
		    	return true;
		    	
		    } else {
		    	
		    	return false;
		    }
	    
	    } else {
	    	
	    	return false;	    	
	    }
	}
	
	/**
	 * 
	 * 获取邮件报告列表
	 * 
	 * @return array
	 */
	static function getEDMList()
	{
		self::_getToken();
		$emailLists = self::$client->emailGet(self::$token, "", "", 1, 10, "", "");
		
		//print_r($emailLists);
		//exit;
		
		foreach($emailLists as $k => $v) {
			
			if ($v["status"] == "Scheduled" or $v["status"] == "Draft") { 
				
				$emailLists[$k]["mailSent"] = '-';
				$emailLists[$k]["opens"] = '-';
				$emailLists[$k]["clicks"] = '-';
				$emailLists[$k]["bounces"] = '-';
				$emailLists[$k]["unsubscribes"] = '-';
				$emailLists[$k]["forwards"] = '-';
				$emailLists[$k]["abuseReports"] = '-';
			
				continue; 
			}
			
			$summary = self::$client->reportGetSummary(self::$token, $v['id']); 
			$emailLists[$k]["mailSent"] = $summary["mailSent"];
			$emailLists[$k]["opens"] = $summary["opens"];
			$emailLists[$k]["clicks"] = $summary["clicks"];
			$emailLists[$k]["bounces"] = $summary["bounces"];
			$emailLists[$k]["unsubscribes"] = $summary["unsubscribes"];
			$emailLists[$k]["forwards"] = $summary["forwards"];
			$emailLists[$k]["abuseReports"] = $summary["abuseReports"];
		}
		
		return $emailLists;
		
	}
	
	/**
	 * 
	 * 获取客户邮箱组列表
	 * 
	 * @return array
	 */
	static function getMailGroupList() {
		
		self::_getToken();
		$contactList = self::$client->listGet(self::$token, "", 1, 10, "", "");
		
		return $contactList;
		
	}
	
	/**
	 * 
	 * 添加客户信息到制定的客户邮箱组列表
	 * @param string $listID
	 * @param array $customerInfo
	 * @return 添加成功的记录数
	 */
	static function addMailToMailGroup($listID, $customerInfo) {
		
		self::_getToken();
		$added_counts = self::$client->listAddContacts(self::$token, $listID, $customerInfo);

		return $added_counts;
	}
	
	/**
	 * 
	 * 从客户邮箱组列表中删除制定邮箱
	 * @param string $listID
	 * @param string $email
	 */
	static function delMailFromMailGroup($listID, $email) {
		
		self::_getToken();
		$del_counts = self::$client->listDeleteEmailContact(self::$token, $listID, $email);

		return $del_counts;
	}
	
	/**
	 * 
	 * 获取邮件列表清单
	 * 
	 * @param String $year 年份
	 * @return array
	 */
	static function getSourceMailFolderNameList($year="2013",$site="iwowcase.com") {
		
		$opt = array('http' => array('proxy' => Q::ini('custom_api/proxy_host') . ':' . Q::ini('custom_api/proxy_port'), 'request_fulluri' => true));
		$context = stream_context_create($opt);
		$mailFolderNameString = file_get_contents("http://email.{$site}/scan_list.php?year={$year}", false, $context);
		$mailFolderNameList = explode("||", $mailFolderNameString);
		
		return $mailFolderNameList;
		
	}
	
	/**
	 * 
	 * 获取邮件 html 内容
	 * 
	 * @param String $mailFolderName 邮件目录名称
	 * @param String $year 年份
	 * @return array
	 */
	static function getSourceMailContent($mailFolderName, $year="2013", $site="iwowcase.com") {
		
		$opt = array('http' => array('proxy' => Q::ini('custom_api/proxy_host') . ':' . Q::ini('custom_api/proxy_port'), 'request_fulluri' => true));
		
		$context = stream_context_create($opt);
		
		$source_email_dir = "http://email.{$site}/{$year}/{$mailFolderName}/";
		
		$html_contents = file_get_contents($source_email_dir."index.html", false, $context);
		
		preg_match_all("|<title>(.*)<\/title>([^*]+)<body [^>]+>([^\|]+)<\/body>|",$html_contents,$r_match);

		$a_r["name"] = substr ( $mailFolderName, 0, 9 ) . ( substr( $site, 0, 4) ) . "_" . substr ( $mailFolderName, 9 );
		$a_r["subjects"] = $r_match[1][0];
		$a_r["html_contents"] = $r_match[3][0];
		$a_r["html_contents"] = preg_replace("/img src=\"images\//", "img src=\"{$source_email_dir}images/", $a_r["html_contents"]);
		$a_r["schedule_date"] = date("j F Y ", strtotime ( substr ( $mailFolderName, 0, 8 ) ))."13:00";
		
		return $a_r;
		
	}
	
	
	
}

?>